const multiparty = require("multiparty");
const path = require("path");
const fse = require("fs-extra");
const { hostname } = require("os");
const querystring = require('querystring');
const { dir } = require("console");
//上传目录
const UPLOAD_DIR = path.resolve(__dirname, "static/upload");
// 单文件上传
async function singleUpload(req, res) {
    let multipart = new multiparty.Form();
    multipart.parse(req, async (err, fields, file) => {
        let filename = fields.filename[0];
        let chunk = file.chunk[0];
        /* 根据时间设置文件夹名称  */
        let date = new Date();
        // 根路径  static/upload   2020-6-26 
        let chunkDir = path.resolve(UPLOAD_DIR, `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`);
        /* 不存在目录则创建 */
        if (!fse.existsSync(chunkDir)) {
            fse.mkdirSync(chunkDir);
        }
        let imgSrc = `http://${req.headers.host}/static/upload/${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}/${filename}`;
        /* 将文件放置到目录 */
        let rs = fse.createReadStream(chunk.path),
            ws = fse.createWriteStream(path.resolve(chunkDir, filename));
        rs.pipe(ws);
        ws.on('close', function () {
            console.log("上传成功");
            res.end(JSON.stringify({ msg: 'ok', imgSrc }))
        })
    })
}
//base64编码上传
async function base64Upload(req, res) {
    let { chunk, filename } = await getPostData(req);
    chunk = decodeURIComponent(chunk).replace(/^data:image\/\w+;base64,/, "");
    let dataBuffer = Buffer.from(chunk, 'base64');
    // 路径
    /* 根据时间设置文件夹名称  */
    let date = new Date();
    // 根路径  static/upload   2020-6-26 
    let chunkDir = path.resolve(UPLOAD_DIR, `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`);
    /* 不存在目录则创建 */
    if (!fse.existsSync(chunkDir)) {
        fse.mkdirSync(chunkDir);
    }
    fse.writeFile(path.join(chunkDir, filename), dataBuffer, (err) => {
        if (err) {
            console.log(err)
            res.end(JSON.stringify(err));
        } else {
            let imgSrc = "http://" + req.headers.host + '/static/upload/' + `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}/` + filename;
            console.log("上传成功");
            res.end(JSON.stringify({ msg: "上传成功", imgSrc }));
        }
    })
}
//切片上传
async function chunkUpload(req, res) {
    let multipart = new multiparty.Form();
    multipart.parse(req, (err, fields, file) => {
        if (err) {
            return res.end(JSON.stringify({
                code: 1,
                msg: "参数错误"
            }));
        }
        let filename = fields.filename[0],
            dirname = fields.dirname[0];
        let chunk = file.chunk[0];
        // 文件夹
        let chunkDir = path.resolve(UPLOAD_DIR, dirname);
        if (!fse.existsSync(chunkDir)) {
            fse.mkdirSync(chunkDir);
        }
        //写入
        let rs = fse.createReadStream(chunk.path);
        let ws = fse.createWriteStream(path.resolve(chunkDir, filename));
        rs.pipe(ws);
        rs.on('end', () => {
            console.log("上传成功");
            res.end(JSON.stringify({
                code: 0,
                msg: "上传成功"
            }))
        })

    })
}
//合并
async function mergeUpload(req, res) {
    let { filename } = await getPostData(req);
    let date = new Date();
    let filePath = path.resolve(UPLOAD_DIR, `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`, filename);
    //目标文件夹
    let chunkDir = path.resolve(UPLOAD_DIR, `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`);
    /* 不存在目录则创建 */
    if (!fse.existsSync(chunkDir)) {
        fse.mkdirSync(chunkDir);
    }
    // 获取文件夹下目录名称
    let dirName = filename.slice(0, filename.lastIndexOf('.'));
    let dirPath = path.resolve(UPLOAD_DIR, dirName);
    let pathList = fse.readdirSync(dirPath);
    // 目录排序合并
    pathList.sort((a, b) => a.localeCompare(b)).forEach(item => {
        let itemPath = `${dirPath}/${item}`;
        console.log(itemPath);
        fse.appendFileSync(filePath, fse.readFileSync(itemPath));
        fse.unlinkSync(itemPath);
    })
    fse.rmdirSync(dirPath);
    let imgSrc = `http://${req.headers.host}/static/upload/${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}/${filename}`;
    res.end(JSON.stringify({
        msg: '合并成功',
        imgSrc
    }))
}
// 获取post数据的方法
function getPostData(req) {
    return new Promise((resolve) => {
        let postData = "";
        req.addListener("data", (data) => postData += data);
        req.addListener('end', () => {
            postData = querystring.parse(postData);
            resolve(postData);
        })
    })
}

module.exports = {
    singleUpload,
    base64Upload,
    chunkUpload,
    mergeUpload
}

